package com.zsd.android.recyclerviewlibrary.manager;

import android.support.v4.util.SparseArrayCompat;

import com.zsd.android.recyclerviewlibrary.holder.RViewHolder;
import com.zsd.android.recyclerviewlibrary.listener.RViewItem;

public class RViewItemManager<T> {

    private SparseArrayCompat<RViewItem<T>> styles;

    public RViewItemManager() {
        styles = new SparseArrayCompat<>();
    }

    public void addItem(RViewItem<T> item) {
        if (item != null) {
            styles.put(styles.size(), item);
        }
    }

    public RViewItem<T> getItem(int viewType) {
        return styles.get(viewType);
    }

    public void convertView(RViewHolder holder, T data, int position) {
        for(int i = styles.size() - 1; i >= 0; i--) {
            RViewItem<T> item = styles.valueAt(i);
            if (item.isItemView(data, position)) {
                item.convertView(holder, data, position);
                return;
            }
        }
        throw new IllegalArgumentException(position + "位置没有匹配的条目样式");
    }

    public int getItemStyleCount() {
        return styles.size();
    }

    public int getItemStyle(T data, int position) {
        for(int i = styles.size() - 1; i >= 0; i--) {
            RViewItem<T> item = styles.valueAt(i);
            if (item.isItemView(data, position)) {
                return styles.keyAt(i);
            }
        }
        throw new IllegalArgumentException(position + "位置没有匹配的条目样式");
    }
}
